package com.horay.statemachiedemo.multi.persist.config;

import com.horay.statemachiedemo.multi.enums.FormState;
import com.horay.statemachiedemo.multi.event.FormEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.persist.RepositoryStateMachinePersist;
import org.springframework.statemachine.redis.RedisStateMachineContextRepository;
import org.springframework.statemachine.redis.RedisStateMachinePersister;

/**
 * Class description
 *
 * @author heyingcheng
 * @date 2020/10/23
 */
@Configuration("formRedisPersistConfig")
public class FormRedisPersistConfig {

    private final RedisConnectionFactory redisConnectionFactory;

    public FormRedisPersistConfig(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    /**
     * 注入RedisStateMachinePersister对象
     *
     * @author heyingcheng
     * @date 2020/10/23
     */
    @Bean
    public RedisStateMachinePersister<FormState, FormEvent> formRedisStateMachinePersister() {
        return new RedisStateMachinePersister<>(formRedisStateMachinePersist());
    }

    /**
     * 通过redisConnectionFactory创建StateMachinePersist
     *
     * @author heyingcheng
     * @date 2020/10/23
     */
    public StateMachinePersist<FormState, FormEvent, String> formRedisStateMachinePersist() {
        RedisStateMachineContextRepository<FormState, FormEvent> repository = new RedisStateMachineContextRepository<>(redisConnectionFactory);
        return new RepositoryStateMachinePersist<>(repository);
    }

}
